﻿//--------------------------------------------------------------------------------------------------------------
// <copyright file="CSPMembershipRequestWUC.cs" company="Microsoft Corporation" date="01/01/2008">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------


using System;
using System.Collections;
using System.Data;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Security;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;


namespace CSP.WebParts.UserControls
{
    /// <summary>
    /// Shows the list of the memebeship requests, allows to accpet
    /// </summary>  
    public class CSPMembershipRequestListWUC : CSPBaseWUC
    {      

        #region Members
        protected GridView gvMembershipRequestList;
        DataTable requestsTable;
    
        #endregion

    
        #region properties
        public int PageSize { get; set; }
        #endregion

        #region PageEvents
        /// <summary>
        /// Fired on page load
        /// </summary>  
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                if (!Page.IsPostBack)
                {
                    
                    this.LoadData();
                }
            }                       
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipRequestListLoadErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }


        /// <summary>
        /// Fired on create child controls
        /// </summary>  
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {                   
                gvMembershipRequestList.RowCommand += new GridViewCommandEventHandler(gvMembershipRequestList_RowCommand);
                gvMembershipRequestList.PageIndexChanging += new GridViewPageEventHandler(gvMembershipRequestList_PageIndexChanged);
                gvMembershipRequestList.Sorting  += new GridViewSortEventHandler (gvMembershipRequestList_SortCommand);
                 if (this.PageSize != 0)
                    gvMembershipRequestList.PageSize = this.PageSize;
               
            }          
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipRequestListCreateChildControlsErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }
        #endregion


        #region Methods
            /// <summary>
            /// Gets the membership request list
            /// </summary>
            protected void LoadData()
            {
                MembershipInterface.MembershipServiceClient client = null;
                try
                {
                    client = new CSP.MembershipInterface.MembershipServiceClient();
                    CSP.MembershipInterface.ObjectModel.CitizenRequest[] requests = new CSP.MembershipInterface.ObjectModel.CitizenRequest[0];
                    requests = client.GetCitizenRequests();

                    //CSP.MembershipInterface.ObjectModel.CitizenRequest[] requests = client.GetCitizenRequests();

                    
                    if (requests == null || requests.Length == 0)
                    {
                        this.gvMembershipRequestList.Visible = false;
                        WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPEmptyListMessage));
                    }
                    else
                    {

                        requestsTable = new DataTable();

                        requestsTable.Columns.Add("Name", typeof(string));
                        requestsTable.Columns.Add("Address", typeof(string));
                        requestsTable.Columns.Add("Phone", typeof(string));
                        requestsTable.Columns.Add("CitizenRequestTypeTitle", typeof(string));
                        requestsTable.Columns.Add("Username", typeof(string));

                        foreach (MembershipInterface.ObjectModel.CitizenRequest request in requests)
                        {
                            requestsTable.Rows.Add(new object[] { request.FirstName + " " + request.LastName, request.Address, request.Phone, request.RequestType.ToString(), request.Username });
                        }

                        DataView dataView = requestsTable.DefaultView;

                        if (ViewState["SortExp"] != null && ViewState["SortDir"] != null)
                        {
                            dataView.Sort = ViewState["SortExp"] + " " + ViewState["SortDir"];
                        }

                        this.gvMembershipRequestList.DataSource = dataView.ToTable();
                        this.gvMembershipRequestList.DataBind();

                    }
                }
                catch (Exception ex)
                {
                    this.LogMessage(this.LoadResource(WebPartConstants.CSPEndPointErrorMessage), this.GetType().Name, ex);
                    throw new CSP.Core.CSPException(ex);
                }
                finally
                {
                    if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
                        client.Close();
                }
            
            }
        #endregion
       

        #region ControlEvents
            /// <summary>
            /// Fired on gridview sorting
            /// </summary> 
            protected void gvMembershipRequestList_SortCommand(object sender, GridViewSortEventArgs e)
            {
                try
                {
                    base.GridViewSortCommand(((GridView)sender), e);                    
                }
                catch (Exception ex)
                {
                    this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipRequestListSortingErrorMessage), this.GetType().Name, ex);
                    throw new CSP.Core.CSPException(ex);
                }
            }

            /// <summary>
            /// Fired on gridview paging
            /// </summary> 
            protected void gvMembershipRequestList_PageIndexChanged(object sender, GridViewPageEventArgs e)
            {
                try
                {
                    base.GridViewPageChangedCommand(((GridView)sender), e);
                    this.LoadData();
                }               
                catch (CSP.Core.CSPException cspex)
                {
                    throw cspex;
                }
                catch (Exception ex)
                {
                    this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipRequestListPagingErrorMessage), this.GetType().Name, ex);
                    throw ex;
                }
            }


            /// <summary>
            /// Fired on gridview command. Approve or Deny
            /// </summary> 
            protected void gvMembershipRequestList_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                try
                {
                    if ((e.CommandName == "Approve") || (e.CommandName == "Deny"))
                    {

                        int index = Convert.ToInt32(e.CommandArgument);
                        GridViewRow selectedRow = ((GridView)sender).Rows[index];

                        string username = selectedRow.Cells[0].Text;
                        string argument = selectedRow.Cells[4].Text;

                        MembershipInterface.MembershipServiceClient client = null;
                        try
                        {
                            client = new MembershipInterface.MembershipServiceClient();

                            if (e.CommandName == "Approve")
                            {
                                MembershipInterface.ObjectModel.CitizenRequest request = client.GetCitizenRequestByUsername(username);
                                if (request != null)
                                {

                                    if (argument == "Add")
                                    {
                                        MembershipUser existingUser = System.Web.Security.Membership.GetUser(username);
                                        if (existingUser != null)
                                        {
                                            System.Web.Security.Membership.DeleteUser(username, true);
                                        }
                                        MembershipCreateStatus createStatus;
                                        System.Web.Security.Membership.CreateUser(username, request.Password, request.EmailAddress, null, null, true, out createStatus);

                                        if (createStatus == MembershipCreateStatus.Success)
                                        {
                                            //Add the user to the default group
                                            SPWeb web = SPControl.GetContextSite(Context).RootWeb;
                                            web.SiteGroups[LoadResource("CSP_citizensgroup_title")].AddUser(string.Format("{0}:{1}", System.Web.Security.Membership.Provider.Name.ToLower(), username.ToLower()), request.EmailAddress, request.FirstName + " " + request.LastName, "Self Registration");
                                            client.ApproveCitizenRequest(username);

                                            //email user to confirm that request is approved
                                            //xsltValues = new Hashtable(1);
                                            //xsltValues.Add("cks:MembershipRequest", request);
                                            //Email.SendEmail(web, request.UserEmail, string.Format("{0}/_layouts/FBA/emails/MembershipApproved.xslt", web.Url), xsltValues);


                                        }
                                        else
                                        {
                                            //throw new Exception(WebPartConstants.CSPMembershipRequestListCreateuUserErrorMessage);
                                        }

                                    }
                                    else {
                                        client.ApproveCitizenRequest(username);
                                    }

                                    

                                }
                            }
                            else if (e.CommandName == "Deny")
                            {
                                client.DenyCitizenRequest(username);
                            }
                        }
                        catch (CSP.Core.CSPException cspex)
                        {
                            throw cspex;
                        }
                        catch (Exception ex)
                        {
                            this.LogMessage(this.LoadResource(WebPartConstants.CSPGenericErrorMessage), this.GetType().Name, ex);
                            throw ex;
                        }


                        finally
                        {
                            if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
                                client.Close();
                        }
                        this.LoadData();
                    }
                }
                catch (CSP.Core.CSPException cspex)
                {
                    throw cspex;
                }
                catch (Exception ex)
                {
                    this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipRequestListRowCommandErrorMessage), this.GetType().Name, ex);
                    throw new CSP.Core.CSPException(ex);
                }
            }
        #endregion

    }
}
